//
//  ViewController.swift
//  1.19.Loading Web Pages with WebKit
//
//  Created by joker on 15/7/22.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController,  WKNavigationDelegate {

    var webView: WKWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = false
        
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences
        
        webView = WKWebView(frame: view.bounds, configuration: configuration)
        
        if let theWebView = webView {
            let url = NSURL(string: "http://www.baidu.com")
            let urlrequest = NSURLRequest(URL: url!)
            theWebView.loadRequest(urlrequest)
            theWebView.navigationDelegate = self
            view.addSubview(theWebView)
        }
    }

    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }
    
    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .LinkActivated {
            decisionHandler(.Cancel)
            let alertController = UIAlertController(title: "Action not allowed", message: "Tapping on links is not allowed. Sorry!", preferredStyle: .Alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            
            presentViewController(alertController, animated: true, completion: nil)
            return
        }
        decisionHandler(.Allow)
    }
}

